package com.westvalley.common.kit;

import java.util.UUID;
import java.util.Map.Entry;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

public class ModelKit {
	
	public static <T> T newModel(Class<T> modelClass){
		if(modelClass != null){
			try {
				return modelClass.newInstance();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return null;
	}
	
	public static Model<?> toModel(Class<? extends Model<?>> modelClass,Record record){
		Model<?> model = newModel(modelClass);
		model._setAttrs(record.getColumns());
		return model;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T modelMapping(Class<T> modelClass,Model<?> model){
		T t = null;
		if(modelClass != null && model!=null){
			t = newModel(modelClass);
			if(t instanceof Model){
				Model<?> newModel =  (Model<?>)t;
				Table table = getTable(newModel.getClass());
				if(table!=null){
					for(Entry<String, Object> entry : model._getAttrsEntrySet()){
						if(table.hasColumnLabel(entry.getKey()))
							newModel.set(entry.getKey(), entry.getValue());
					}
					return (T) newModel;
				}
			}
		}
		return t;
	}
	
	public static String getUUID(){
		return UUID.randomUUID().toString();
	}
	
	@SuppressWarnings("rawtypes")
	public static Table getTable(Class<? extends Model> clazz){
		return TableMapping.me().getTable(clazz);
	}
	
	
}
